/*
 * @Author: your name
 * @Date: 2019-11-04 13:45:22
 * @LastEditTime: 2019-11-05 15:18:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \mqtt-tool-app\src\app\home\home.page.ts
 */
import { Component, ChangeDetectorRef } from '@angular/core';

declare var chrome;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  private socketTcpId ;
  tcpRecvData ;

  constructor(private changeDetectorRef: ChangeDetectorRef) {
    // setInterval(() => {this.tcpRecvData++; } , 1000);
  }
  public ab2str(buf) {
    let result = '';
    if (buf) {
        const bytes = new Uint8Array(buf);
        for (let i = 0; i < bytes.byteLength; i++) {
            result = result + String.fromCharCode(bytes[i]);
        }
    }
    return result;
  }
  public str2ab(str) {
    const buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
    const bufView = new Uint16Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }
  public tcpConnectToServer() {
    chrome.sockets.tcp.create({}, createInfo => {
      this.socketTcpId = createInfo.socketId;
      chrome.sockets.tcp.onReceive.addListener(this.tcpRecv);
      chrome.sockets.tcp.onReceiveError.addListener(this.tcpError);
      chrome.sockets.tcp.connect(this.socketTcpId, '192.168.1.154', 12345, result => {
        console.log('Connected to server');
      });
    });
  }
  public tcpSend() {
    chrome.sockets.tcp.send(this.socketTcpId, this.str2ab('12312312321312312312'));
  }
  tcpError = ({socketId, resultCode}) => {
    console.log('tcp_recv_error', socketId, resultCode);
  }
  tcpRecv = ({socketId, data}) => {
    if ( this.socketTcpId !== socketId) { return ; }
    this.tcpRecvData = this.ab2str(data);
    console.log(this.tcpRecvData);
    this.changeDetectorRef.detectChanges();
  }
}
